package com.yuqiangz.springsecurity.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @author zhaoyuqiang
 * @create 2024/5/14 7:20
 * @description
 */
public class JwtUtil {

    //有效期
    public static final Long JWT_TTL = 60 * 60 * 1000L;
    public static  final String JWT_KEY = "sangeng";

    /**
     * 生成加密后的秘钥 secretKey
     * @return
     */
    public static SecretKey generalKey(){
        byte[] decodeKey = Base64.getDecoder().decode(JWT_KEY);
        return new SecretKeySpec(decodeKey, 0, decodeKey.length, "AES");
    }

    public static String getUUID(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid){
        SignatureAlgorithm hs256 = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);


        if(ttlMillis == null){
            ttlMillis = JwtUtil.JWT_TTL;
        }

        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);

        return Jwts.builder().setId(uuid).setSubject(subject).setIssuer("sg").setIssuedAt(now).signWith(hs256, secretKey).setExpiration(expDate);
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据（json格式）
     * @return
     */
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
        return builder.compact();
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据（json格式）
     * @param ttlMillis token超时时间
     * @return
     */
    public static String createJWT(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
        return builder.compact();
    }

    public static String createJWT(String subject, Long ttlMillis,String id) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
        return builder.compact();
    }

    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }


    public static void main(String[] args) throws Exception {
        String jwt = createJWT("2123");
        System.out.println(jwt);
        Claims claims = parseJWT(jwt);
        String subject = claims.getSubject();
        System.out.println(subject);
//        System.out.println(claims);
    }

}
